/**
 *大众点评网 爬虫
 *
 */
// not strict mode


var fs = require('fs');
var path = require('path');
var promise = require('promise');
var request = require('request');
var sha1 = require('sha1');


var __appKey = '1004300741';
var __appSecret = '91d31e7c07534f55a42d3f53d965b40a';
var __appName = 'api_test_v1';
var __baseUrl = 'http://api.dianping.com/v1';
var __dataFolder = path.join(__dirname, 'data');
var __format = 'json';
var __fileExtension = '.json';

// api传递的参数
var __city = '广州';
var __region = '天河区';
var __category = '丽人';
var __radius = 5000;
var __limit = 40;
var __page = 1;
var __keyword = '';

function DzdpApi() {}

// 生成sign的api
DzdpApi.prototype.getSign = function(param) {
    // console.log(param);

    var arr = [];
    for (var key in param) {
        if (key !== 'appkey' && key !== 'sign') {
            arr.push(key);
        }
    }
    arr.sort();

    var paramArr = [];
    paramArr.push(__appKey);
    arr.forEach(function(key) {
        paramArr.push(key + param[key]);
    });
    paramArr.push(__appSecret);
    var shaSource = paramArr.join('');
    var sign = new String(sha1(shaSource)).toUpperCase();
    return sign;
};

DzdpApi.prototype.paramToQs = function(param) {
    var sign = this.getSign(param);
    var arr = [];
    for (var key in param) {
        var value = param[key];
        arr.push(key + '=' + encodeURIComponent(value));
    }
    arr.push('sign=' + sign);
    var qs = arr.join('&');
    var qs = '?' + qs;
    return qs;
};

DzdpApi.prototype.getSaveFileName = function(rUrl) {
    var fileName = rUrl.split('/').pop();
    return path.join(__dataFolder, fileName + __fileExtension);
};

DzdpApi.prototype.httpGetThenSave = function(rUrl, param, cb) {
    var fileName = this.getSaveFileName(rUrl);
    var url = __baseUrl + rUrl + this.paramToQs(param);
    // console.log(url);

    //
    __promiseGet(url).then(function fullfil(result) {
        // save to file
        fs.writeFile(fileName, result, function(err) {
            if (err) {
                return console.log('write file err' + err);
            }
            // console.log('-------------success-----------');
            // console.log(fileName);
            if (cb) cb(null, result);
        });
    }, function reject(err) {
        console.log(err);
        if (cb) cb(err);
    });
};

/**inner function*/
function __promiseGet(url) {
    return new Promise(function(resolve, reject) {
        request.get(url, function(err, response, body) {
            if (err) {
                reject(err);
                return;
            }
            resolve(body);
        });
    });
}

/***----------------api ------------------*/
DzdpApi.prototype.get_categories_with_businesses = function() {
    var rUrl = '/metadata/get_categories_with_businesses';
    var param = {
        appkey: __appKey,
        city: __city
    };
    this.httpGetThenSave(rUrl, param);
};


DzdpApi.prototype.get_cities_with_businesses = function() {
    var rUrl = '/metadata/get_cities_with_businesses';
    var param = {
        appkey: __appKey
    };
    this.httpGetThenSave(rUrl, param);
};

DzdpApi.prototype.get_regions_with_businesses = function() {
    var rUrl = '/metadata/get_regions_with_businesses';
    var param = {
        appkey: __appKey,
        city: __city
    };
    this.httpGetThenSave(rUrl, param);
};

DzdpApi.prototype.find_businesses = function() {
    var rUrl = '/business/find_businesses';
    var param = {
        // radius: __radius,
        appkey: __appKey,
        city: __city,
        region: __region,
        category: __category,
        limit: __limit,
        page: __page,
        // keyword: __keyword,
    };
    this.httpGetThenSave(rUrl, param);
};

/**
 * 获取当前在线的全部团购ID列表
 */
DzdpApi.prototype.get_all_id_list = function() {
    var rUrl = '/deal/get_all_id_list';
    var param = {
        appkey: __appKey,
        city: __city,
    };
    this.httpGetThenSave(rUrl, param);
};

/**
 * 搜索团购 Deal/find_deals
 */
DzdpApi.prototype.find_deals = function() {
    var rUrl = '/deal/find_deals';
    var param = {
        appkey: __appKey,
        city: __city,
        category: __category,
        page: __page,
        limit: __limit
    };
    this.httpGetThenSave(rUrl, param);
};

/**
 * 搜索团购 Deal/find_deals
 */
DzdpApi.prototype.get_single_deal = function(dealId) {
    var rUrl = '/deal/get_single_deal';
    var param = {
        appkey: __appKey,
        deal_id: dealId //"4-6447514",
    };
    this.httpGetThenSave(rUrl, param);
};

/**
 * 获取指定商户的团购信息 deal/get_deals_by_business_id
 * 6210157
 */
DzdpApi.prototype.get_deals_by_business_id = function(businessId) {
    var rUrl = '/deal/get_deals_by_business_id';
    var param = {
        appkey: __appKey,
        city: __city,
        business_id: businessId //"21079612"
    };
    this.httpGetThenSave(rUrl, param);
};

/**
 *  获取指定商户信息
 */
DzdpApi.prototype.get_single_business = function(businessId, cb) {
    var rUrl = '/business/get_single_business';
    var param = {
        appkey: __appKey,
        business_id: businessId
    };
    this.httpGetThenSave(rUrl, param, cb);
};


// var api = new DzdpApi();
//api.get_categories_with_businesses();
//api.get_cities_with_businesses();
//api.get_regions_with_businesses();
//api.find_businesses();
//api.get_all_id_list();
//api.find_deals();
//api.get_single_deal();
// api.get_deals_by_business_id();
// api.get_single_business('23113469');

module.exports = DzdpApi;